Categories
Node.js Tips

Node.js Tips — MongoDB and SQL

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

MongoDB Driver async/await Queries

The MongoDB Node drive supports promises, so we can use async and await in our queries.

For instance, we can write:

const MongoClient = require('mongodb').MongoClient;
const connectionString = 'mongodb://localhost:27017';

(async () => {
  const client = await MongoClient.connect(
    connectionString, {
      useNewUrlParser: true
    }
  );
  const db = client.db('dbName');
  try {
    const res = await db.collection("collectionName")
      .updateOne({
        "foo": "bar"
      }, {
        $set: {}
      }, {
        upsert: true
      });
    console.log(res);
  } finally {
    client.close();
  }
})()

We call MongoClient.connect with the connectionString .

Then we get the database to manipulate with client.db .

We then use the db.collection method to get the collection to query.

Then we call updateOne to update the entry with the given field with the value.

Pressing Enter Button in Puppeteer

We can press the Enter button with Puppeteer by writing:

await page.type(String.fromCharCode(13));

13 is the key code for the Enter key.

Also, we can use the press method on an element.

For example, we can write:

await (await page.$('input[type="text"]')).press('Enter');

We select an input with type text and call press with 'Enter' as the argument.

'\n' and '\r' are also alternatives for 'Enter' , so we can write:

await page.keyboard.press('n');

or:

await page.keyboard.press('r');

To press the Numpad Enter key, we can write:

await (await page.$('input[type="text"]')).press('NumpadEnter');

We select the input with type text and call press with 'NumpadEnter' .

There’s also the sendCharacter method:

await page.keyboard.sendCharacter(String.fromCharCode(13));

Check for undefined Property in EJS for Node.js

We can use the typeof operator to check for an undefined property.

For instance, we can write:

const template = '<% (typeof foo !== "undefined" ? %>foo defined<% : %>foo undefined<% ) %>';

We just use the typeof operator just like in JavaScript.

Then we show foo defined if it’s defined.

Otherwise, we show foo undefined .

Listen to All Interfaces Instead of Localhost Only with Express

We can specify the IP address with app.listen to listen to.

To listen to all address, we can pass in '0.0.0.0' .

For example, we can write:

const express = require('express');
const app = express();

//...
app.listen(3000, '0.0.0.0');

How to Find the Size of the File in Node.js

To find the size of a file, we can use the statSync method.

For instance, we can write:

const fs = require("fs");
const stats = fs.statSync("foo.txt");
const fileSizeInBytes = stats.size;

We call statSync with the file path to get data about the file.

Then we use the size property to get the file size in bytes.

List Available Crypto Algorithms

We can use the crypto module to get the list of algorithms.

To get them, we use the getCiphers to get available ciphers.

And we can also use getHashes to get the available hashes.

So we can write:

const crypto = require('crypto');
console.log(crypto.getCiphers());
console.log(crypto.getHashes());

Set _id to DB Document with Mongoose

To let us set the _id of the database document with Mongoose, we can put the _id property in the Schema.

Or we can ser the _id option to false .

For instance, we can write:

const Person = new mongoose.Schema({
  _id: Number,
  name: String
});

or:

const Person = new mongoose.Schema({
  name: String
}, { _id: false });

All a Where Clause Conditionally to a Knex Query

To add a where clause conditionally to a Knex query, we can store the general query in a variable.

Then we can write:

const query = knex('persons')
  .select('name', 'james')
  .limit(50);

if (age) {
  query.where('age', age);
}

We add the where clause for age only if age is defined.

Or, we can use the modify method.

For instance, we can write:

knex('persons')
  .select('name', 'james')
  .limit(50);
  .modify((queryBuilder) => {
    if (age) {
      queryBuilder.where('age', age);
    }
  });

We make our age query in the callback instead of storing the query in a variable.

Conclusion

The MongoDB Node driver supports promises.

We can press Enter with Puppeteer in many ways.

We can make Knex queries conditionally.

Also, we can listen to all IP addresses with Express apps.

_id can be set if we specify it in the Mongoose schema.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *